package com.tensquare.friend.controller;

import com.tensquare.friend.service.FriendService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 交友Controller.
 *
 * @author 宫新程
 * @since 2019/3/18 0:31
 */
@RestController
@RequestMapping("/friend")
public class FriendController {

  @Resource private FriendService friendService;

  /**
   * 添加好友或非好友.
   *
   * @param friendid 好友ID
   * @param type 类型 1:喜欢 2：不喜欢
   * @return Result
   */
  @PutMapping("/like/{friendid}/{type}")
  public Result addFriend(
      @PathVariable String friendid, @PathVariable Integer type, HttpServletRequest request) {
    // 验证是否登录
    Claims claims = (Claims) request.getAttribute("claims_user");
    if (null == claims) {
      // 说明当前用户没有user权限.
      return new Result(false, StatusCode.ERROR, "请先登录...");
    }

    // 获取当前登录的id.
    String userId = claims.getId();

    // 判断是添加好友，还是非好友
    if (type != null && type.equals(1)) {
      // 添加好友
      int flag = friendService.addFriend(userId, friendid);
      if (flag == 0) {
        return new Result(false, StatusCode.ERROR, "不能重复添加好友");
      } else {
        return new Result(true, StatusCode.OK, "添加成功");
      }
    } else if (type != null && type.equals(2)) {
      // 非好友
      int flag = friendService.deleteFriend(userId, friendid);
      if (flag == 0) {
        return new Result(false, StatusCode.ERROR, "不能重复删除好友");
      } else {
        return new Result(true, StatusCode.OK, "删除成功");
      }
    } else {
      return new Result(false, StatusCode.ERROR, "参数异常");
    }
  }
}
